<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Commodity;

/**
 * CommoditySearch represents the model behind the search form about `backend\models\Commodity`.
 */
class CommoditySearch extends Commodity
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'type', 'icon_url', 'desc', 'details'], 'safe'],
            [['count', 'id'], 'integer'],
            [['purchase_price', 'sale_price'], 'number'],
            [['icon_url'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Commodity::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'count' => $this->count,
            'purchase_price' => $this->purchase_price,
            'sale_price' => $this->sale_price,
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'type', $this->type])
            ->andFilterWhere(['like', 'icon_url', $this->icon_url])
            ->andFilterWhere(['like', 'desc', $this->desc])
            ->andFilterWhere(['like', 'details', $this->details]);

        return $dataProvider;
    }
}
